# -*- coding:utf-8 -*-
"""
this file is used for get the like song for xiami user uid
"""
import re
import urllib

def getULike(uid):
    """
    http://www.xiami.com/space/lib-song/u/300000/page/%d
    from 1 to no more song can be crawled

    all the song are in the format of http://www.xiami.com/song/384570
    beside the value info should be got
    """
    curmax = 100
    resultL = []
    for i in range(1,curmax):
        theurl = "http://www.xiami.com/space/lib-song/u/%s/page/%d"%(str(uid),i)
        print theurl
        midGradeL = getMidGradeLFromPage(theurl)
        if len(midGradeL) == 0:
            break
        resultL.extend(midGradeL)
    return resultL


def getMidGradeLFromPage(theUrl):
    thestr = urllib.urlopen(theUrl).read()
    trregex = "<tr class=\"\" id=\"lib_song(\s|\S)*?</tr>"
    resultL = []
    for trm in re.finditer(trregex,thestr):
        tmpstr = thestr[trm.start():trm.end()]
        resultL.append(getMidGrade(tmpstr))
    return resultL

def getMidGrade(thestr):
    """
    href="/song/384570">
    name="grade" value="5">
    """
    midregex = "href=\"/song/(\d)*?\">"
    graderegex = "name=\"grade\" value=\"\d\""
    
    midm = re.search(midregex,thestr)
    if midm:
        midstr = thestr[midm.start():midm.end()]
        #print midstr
        mid = int(midstr[midstr.rindex('/')+1:midstr.rindex("\"")])
    else:
        raise "no mid for this str%s"%thestr

    gradem = re.search(graderegex,thestr)
    if gradem:
        gradestr = thestr[gradem.start():gradem.end()]
        grade = int(gradestr[gradestr.rindex("\"")-1])
    else:
        raise "no grade for this str %s"%thestr

    return mid,grade
